package com.ridbor001.demo.servlet;

import com.alibaba.excel.EasyExcel;
import com.ridbor001.demo.bean.*;
import com.ridbor001.demo.service.RDBCourseService;
import com.ridbor001.demo.service.RDBEvaluationService;
import com.ridbor001.demo.service.RDBTeacherService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.*;

@WebServlet("/evaluation")
public class RDBEvaluationServlet extends HttpServlet {
    RDBTeacherService rdbTeacherService = new RDBTeacherService();
    RDBEvaluationService evalService = new RDBEvaluationService();
    RDBCourseService rdbCourseService = new RDBCourseService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        HttpSession session = req.getSession();
        RDBUser user = (RDBUser) session.getAttribute("user");
        if (user == null) {
            resp.sendRedirect("rDBLogin.jsp");
            return;
        }

        String action = req.getParameter("action");

        try {
            if (user.isStudent()) {
                handleStudentRequests(req, resp, (RDBStudent) user, action);
            } else if (user.isTeacher()) {
                handleTeacherRequests(req, resp, (RDBTeacher) user, action);
            }
        } catch (SQLException e) {
            throw new ServletException("数据库操作失败", e);
        }
    }

    private void handleStudentRequests(HttpServletRequest req, HttpServletResponse resp,
                                       RDBStudent student, String action)
            throws ServletException, IOException, SQLException {

        if ("list".equals(action)) {
            // 从数据库获取待评价课程
            List<RDBCourse> pendingCourses = evalService.getPendingCourses(student.getStudentId());
            // 获取已评教课程及内容
            Map<RDBCourse, List<RDBEvaluation>> evaluatedCoursesWithDetails =
                    evalService.getEvaluatedCoursesWithDetails(student.getStudentId());
            // 翻译维度（新建 Map 结构，替代 JSP 里的 translate 调用）
            Map<String, String> dimNameMap = evalService.getAllDimensionTranslations(); // 你需要写这个方法返回 <英文维度, 中文维度>


            // 批量获取教师信息提高效率
            Map<String, RDBTeacher> teacherMap = new HashMap<>();
            Set<String> teacherIds = new HashSet<>();
            pendingCourses.forEach(c -> teacherIds.add(c.getTeacherId()));
            evaluatedCoursesWithDetails.keySet().forEach(c -> teacherIds.add(c.getTeacherId()));

            for (String teacherId : teacherIds) {
                RDBTeacher teacher = rdbTeacherService.findTeacherById(teacherId);
                if (teacher != null) {
                    teacherMap.put(teacherId, teacher);
                }
            }

            // 构建课程ID到教师名的映射
            Map<String, String> teacherNames = new HashMap<>();
            for (RDBCourse course : pendingCourses) {
                RDBTeacher teacher = teacherMap.get(course.getTeacherId());
                teacherNames.put(course.getCourseId(), teacher != null ? teacher.getName() : "未知教师");
            }
            for (RDBCourse course : evaluatedCoursesWithDetails.keySet()) {
                RDBTeacher teacher = teacherMap.get(course.getTeacherId());
                teacherNames.put(course.getCourseId(), teacher != null ? teacher.getName() : "未知教师");
            }

            req.setAttribute("teacherNames", teacherNames);
            req.setAttribute("courses", pendingCourses);
            req.setAttribute("evaluatedCoursesWithDetails", evaluatedCoursesWithDetails);
            req.setAttribute("dimensionNames", dimNameMap);
            req.getRequestDispatcher("/rDBEval_list.jsp").forward(req, resp);

        } else if ("view".equals(action)) {
            String courseId = req.getParameter("courseId");
            RDBCourse course = rdbCourseService.findCourseById(courseId);
            if (course == null) {
                throw new ServletException("未找到课程信息: " + courseId);
            }
            req.setAttribute("course", course);
            req.getRequestDispatcher("/rDBEval_form.jsp").forward(req, resp);
        }
    }


    private void handleTeacherRequests(HttpServletRequest req, HttpServletResponse resp,
                                       RDBTeacher teacher, String action)
            throws ServletException, IOException, SQLException {

        if ("stats".equals(action)) {
            // 获取统计数据和评论
            Map<RDBCourse, Map<String, Double>> stats = evalService.getTeacherEvaluationStats(teacher.getTeacherId());

            // 转换为中文维度名
            Map<RDBCourse, Map<String, Double>> translatedStats = new LinkedHashMap<>();
            stats.forEach((course, dimMap) -> {
                Map<String, Double> translated = new LinkedHashMap<>();
                dimMap.forEach((dim, score) -> {
                    translated.put(evalService.translateDimension(dim), score);
                });
                translatedStats.put(course, translated);
            });

            Map<RDBCourse, List<String>> comments = evalService.getTeacherEvaluationComments(teacher.getTeacherId());

            req.setAttribute("stats", translatedStats);
            req.setAttribute("comments", comments);
            req.getRequestDispatcher("/rDBEval_stats.jsp").forward(req, resp);
        }
        else if ("export".equals(action)) {
            handleExport(req, resp, teacher);
        }
    }
    private void handleExport(HttpServletRequest req, HttpServletResponse resp, RDBTeacher teacher) throws IOException, SQLException {
        Map<RDBCourse, List<RDBEvaluation>> evaluations = evalService.getTeacherEvaluationsWithDetails(teacher.getTeacherId());

        // 准备导出数据
        List<RDBTeacherEvaluationExcel> exportData = new ArrayList<>();
        evaluations.forEach((course, evals) -> {
            // 维度平均分
            Map<String, Double> dimAverages = evalService.calculateAverageScores(evals);
            dimAverages.forEach((dim, avg) -> {
                exportData.add(new RDBTeacherEvaluationExcel(
                        course.getCourseName(),
                        dim,
                        avg,
                        "" // 维度平均分行不带评论
                ));
            });

            // 收集评论
            List<String> comments = evalService.collectComments(evals);
            comments.forEach(comment -> {
                exportData.add(new RDBTeacherEvaluationExcel(
                        course.getCourseName(),
                        "评论",
                        null,
                        comment
                ));
            });
        });

        // 设置响应头
        String fileName = "教师评教数据_" + System.currentTimeMillis() + ".xlsx";
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));

        // 使用EasyExcel导出
        EasyExcel.write(resp.getOutputStream(), RDBTeacherEvaluationExcel.class)
                .sheet("评教数据")
                .doWrite(exportData);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");

        // 处理评教提交
        RDBStudent student = (RDBStudent) req.getSession().getAttribute("user");
        RDBEvaluation eval = new RDBEvaluation();
        eval.setEvalId(UUID.randomUUID().toString());
        eval.setStudentId(student.getStudentId());
        eval.setCourseId(req.getParameter("courseId"));
        eval.setEvalTime(LocalDateTime.now());

        // 动态解析评价维度
        String[] dimensions = Optional.ofNullable(req.getParameterValues("dimensions"))
                .orElseGet(() -> new String[]{"teaching_attitude", "teaching_method", "teaching_effect"}); // 默认维度值

// 添加空值校验
        if (dimensions == null || dimensions.length == 0) {
            req.setAttribute("error", "请至少选择一个评价维度");
            req.getRequestDispatcher("/rDBEval_form.jsp").forward(req, resp);
            return;
        }
        Arrays.stream(dimensions).forEach(dim -> {
            int score = Integer.parseInt(req.getParameter(dim + "_score"));
            String comment = req.getParameter(dim + "_comment");
            eval.getItems().add(new RDBEvaluationItem(dim, score, comment));
        });

        try {
            evalService.addEvaluation(eval);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.sendRedirect("evaluation?action=list");
    }

}